package com.baoji.auth.filter;

import com.alibaba.fastjson.JSON;
import com.baoji.auth.model.AccountErrorCode;
import com.baoji.auth.utils.JwtTokenUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * @Date: 2021/09/24/16:29
 * 登录拦截器
 * <p>
 * 该类继承自 UsernamePasswordAuthenticationFilter，重写了其中的2个方法 ,
 * attemptAuthentication：接收并解析用户凭证。
 * successfulAuthentication：用户成功登录后，这个方法会被调用，我们在这个方法里生成 token 并返回。
 */

// 验证用户名密码正确后 生成一个token并将token返回给客户端
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;

        // 默认登录路径为 /login   设置登录URL("api/login)
        // super.setFilterProcessesUrl("api/login");
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        // 从输入流中获取到登录的信息   验证操作 接收并解析用户凭证
        // 创建一个token并调用authenticationManager.authenticate() 让Spring security进行验证
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password")));
    }


    // 验证【成功】后调用的方法
    // 若验证成功 生成 token 和 freshToken 并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {

        User user = (User) authResult.getPrincipal();

        // 从User中获取权限信息
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        String username = user.getUsername();
        String role = authorities.toString();
        // 创建Token
        String token = JwtTokenUtil.createToken(username, role, JwtTokenUtil.TOKEN_EXPIRITION);
        // 创建 Refresh_Token
        String refreshToken = JwtTokenUtil.createToken(username, role, JwtTokenUtil.REFRESH_TOKEN_EXPIRITION);

        // 设置编码 防止乱码问题
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // 在请求头里返回创建成功的 token
        // 设置请求头为带有"Bearer "前缀的token字符串
        response.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token);
        // 返回 refreshToken，token过期时用来校验
        response.setHeader(JwtTokenUtil.REFRESH_TOKEN, JwtTokenUtil.TOKEN_PREFIX + refreshToken);

        // 处理编码方式 防止中文乱码
        response.setContentType("text/json;charset=utf-8");
        // 将反馈塞到 HttpServletResponse中返回给前台
        response.getWriter().write(JSON.toJSONString("登录成功"));
    }

    /**
     * 验证【失败】调用的方法
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        String returnData = "";
        // 账号过期
        if (failed instanceof AccountExpiredException) {
            returnData = AccountErrorCode.CREDENTIALS_EXPIRED.getMessage();
        }
        // 密码错误
        else if (failed instanceof BadCredentialsException) {
            returnData = AccountErrorCode.USERNAME_PASSWORD_ERROR.getMessage();
        }
        // 密码过期
        else if (failed instanceof CredentialsExpiredException) {
            returnData = AccountErrorCode.CREDENTIALS_EXPIRED.getMessage();
        }
        // 账号不可用
        else if (failed instanceof DisabledException) {
            returnData = AccountErrorCode.ACCOUNT_DISABLED.getMessage();
        }
        //账号锁定
        else if (failed instanceof LockedException) {
            returnData = AccountErrorCode.ACCOUNT_LOCKED.getMessage();
        }
        // 用户不存在
        else if (failed instanceof InternalAuthenticationServiceException) {
            returnData = AccountErrorCode.USER_NOT_REGISTER.getMessage();
        }
        // 其他错误
        else {
            returnData = "未知异常";
        }

        // 处理编码方式 防止中文乱码
        response.setContentType("text/json;charset=utf-8");
        // 将反馈塞到HttpServletResponse中返回给前台
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(returnData));
        out.flush();
        out.close();
    }
}

